Imports System
Imports System.Collections.Generic
Imports System.Windows.Forms

Namespace ObjectPushProfileApplication
	Public Partial Class Form1
        Inherits Form

		Public Sub New()
			InitializeComponent()
		End Sub

        Private devList As List(Of C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.Device) = Nothing
        Private OPPService As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.RemoteService = Nothing
        Private networkStream As Net.Sockets.NetworkStream = Nothing
        Private OPPServiceList As List(Of C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.RemoteService)
        Private isAsync As Boolean = True

        Private Sub btnDiscover_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnDiscover.Click
            With cmbDevice
                .Items.Clear()
                .Text = ""
            End With

            With cmbServices
                .Items.Clear()
                .Text = ""
                .Enabled = False
            End With
            btnConnect.Enabled = False
            Me.Cursor = Cursors.WaitCursor
            devList = deviceServicesManager1.DiscoverAllDevices()
            If devList.Count <> 0 Then
                For Each dev As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.Device In devList
                    cmbDevice.Items.Add(dev.Name)
                Next
            End If
            If devList.Count > 0 Then
                cmbServices.Enabled = True
            End If
            btnOperation.Enabled = False
            Me.Cursor = Cursors.Default
        End Sub

        Private Sub cmbServices_Enter(ByVal sender As Object, ByVal e As EventArgs) Handles cmbServices.Enter
            Me.Cursor = Cursors.WaitCursor
            cmbServices.Items.Clear()
            If devList IsNot Nothing AndAlso devList.Count <> 0 Then
                For Each dev As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.Device In devList
                    If dev.Name = cmbDevice.Text Then
                        OPPServiceList = deviceServicesManager1.DiscoverServicesByType(dev, _
                                                C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.ServiceType.OBEXObjectPush)
                        If OPPServiceList IsNot Nothing AndAlso OPPServiceList.Count <> 0 Then
                            For Each remServ As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.RemoteService In OPPServiceList
                                cmbServices.Items.Add(remServ.Name)
                            Next
                        End If
                        Exit For
                    End If
                Next
            End If
            If cmbServices.Items.Count > 0 Then
                btnConnect.Enabled = True
            End If
            btnOperation.Enabled = False
            Me.Cursor = Cursors.Default
        End Sub

        Private Sub btnConnect_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnConnect.Click
            Try
                Me.Cursor = Cursors.WaitCursor
                For Each remote As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.RemoteService In OPPServiceList
                    If cmbServices.Text = remote.Name Then
                        OPPService = remote
                        networkStream = OPPService.Connect()
                        btnConnect.Enabled = False
                        cmbServices.Enabled = False
                        With oppManager1
                            .NetworkStream = networkStream
                            .Connect()
                            AddHandler .ObjectPushCompleted, AddressOf oppManager1_ObjectPushCompleted
                            AddHandler .BusinessCardExchangeCompleted, AddressOf oppManager1_BusinessCardExchangeCompleted
                            AddHandler .BusinessCardPullCompleted, AddressOf oppManager1_BusinessCardPullCompleted
                        End With
                        btnOperation.Enabled = True
                        Exit For
                    End If
                Next

            Catch servEx As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.ServiceConnectionException
                btnConnect.Enabled = True
                cmbServices.Enabled = True
                Microsoft.VisualBasic.MsgBox(servEx.Message, Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                             Microsoft.VisualBasic.MsgBoxStyle.Critical, "Object Push Profile")
            Catch ex As Exception
                btnConnect.Enabled = True
                cmbServices.Enabled = True
                Microsoft.VisualBasic.MsgBox(ex.Message, Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                             Microsoft.VisualBasic.MsgBoxStyle.Critical, "Object Push Profile")
            End Try
            Me.Cursor = Cursors.Default
        End Sub

        Private Sub oppManager1_BusinessCardPullCompleted(ByVal sender As Object, _
                                                           ByVal e As C4F.DevKit.Bluetooth.ObjectPushProfile.BusinessCardPullCompletedEventArgs)
            If isAsync Then
                If e.Error Is Nothing Then
                    Dim cardName As String = txtOutputFolder.Text & "\" & e.RemoteCardName
                    Dim i As Integer = 1
                    If IO.File.Exists(cardName) Then
                        Dim extension As String = cardName.Substring(cardName.LastIndexOf(".") + 1)
                        cardName = cardName.Remove(cardName.LastIndexOf("."))
                        While IO.File.Exists(cardName & " (" & i & ")" & "." & extension)
                            i += 1
                        End While
                        cardName = cardName & " (" & i & ")" & "." & extension
                    End If
                    IO.File.WriteAllBytes(cardName, e.RemoteCardContents)
                    Microsoft.VisualBasic.MsgBox("Business Card Pull Complete. " & Environment.NewLine & "Received File: " & cardName _
                                                 , Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or Microsoft.VisualBasic.MsgBoxStyle.Information, _
                                                 "Object Push Profile")

                Else
                    Dim errorMsg As String = e.Error.Message
                    If e.Error.InnerException IsNot Nothing Then
                        errorMsg = errorMsg & Environment.NewLine & "Error Details: " & e.Error.InnerException.Message
                    End If
                    Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                                 Microsoft.VisualBasic.MsgBoxStyle.Critical, "Object Push Profile")
                End If
            Else
                isAsync = True
            End If
        End Sub

        Private Sub oppManager1_BusinessCardExchangeCompleted(ByVal sender As Object, _
                                                               ByVal e As C4F.DevKit.Bluetooth.ObjectPushProfile.BusinessCardExchangeCompletedEventArgs)
            If isAsync Then
                If e.Error Is Nothing Then
                    Dim cardName As String = txtOutputFolder.Text & "\" & e.OutputCardName
                    Dim i As Integer = 1
                    If IO.File.Exists(cardName) Then
                        Dim extension As String = cardName.Substring(cardName.LastIndexOf(".") + 1)
                        cardName = cardName.Remove(cardName.LastIndexOf("."))
                        While IO.File.Exists(cardName & " (" & i & ")" & "." & extension)
                            i += 1
                        End While
                        cardName = cardName & " (" & i & ")" & "." & extension
                    End If
                    IO.File.WriteAllBytes(cardName, e.RemoteCardContents)
                    Microsoft.VisualBasic.MsgBox("Business Card Exchange Complete. " & Environment.NewLine & "File Sent: " & _
                                                 e.LocalCardName & Environment.NewLine & "Received File: " & cardName, _
                                                 Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or Microsoft.VisualBasic.MsgBoxStyle.Information, _
                                                 "Object Push Profile")
                Else
                    Dim errorMsg As String = e.Error.Message
                    If e.Error.InnerException IsNot Nothing Then
                        errorMsg = errorMsg & Environment.NewLine & "Error Details: " & e.Error.InnerException.Message
                    End If
                    errorMsg = errorMsg & Environment.NewLine & "Input File: " & e.LocalCardName
                    Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                                 Microsoft.VisualBasic.MsgBoxStyle.Critical, "Object Push Profile")
                End If
            Else
                isAsync = True
            End If
        End Sub

        Private Sub oppManager1_ObjectPushCompleted(ByVal sender As Object, _
                                                     ByVal e As C4F.DevKit.Bluetooth.ObjectPushProfile.ObjectPushCompletedEventArgs)
            If isAsync Then
                If e.Error Is Nothing Then
                    Microsoft.VisualBasic.MsgBox("Object push completed. " & Environment.NewLine & "File Sent: " & e.LocalObjectName, _
                                                 Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or Microsoft.VisualBasic.MsgBoxStyle.Information, _
                                                 "Object Push Profile")
                Else
                    Dim errorMsg As String = e.Error.Message
                    If e.Error.InnerException IsNot Nothing Then
                        errorMsg = errorMsg & Environment.NewLine & "Error Details: " & e.Error.InnerException.Message
                    End If
                    errorMsg = errorMsg & Environment.NewLine & "Input File: " & e.LocalObjectName
                    Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                                 Microsoft.VisualBasic.MsgBoxStyle.Critical, "Object Push Profile")
                End If
            Else
                isAsync = True
            End If
        End Sub

        Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
            Me.Cursor = Cursors.WaitCursor
            btnConnect.Enabled = False
            cmbServices.Enabled = False
            txtOutputFolder.Text = Environment.CurrentDirectory
            devList = deviceServicesManager1.DiscoverAllDevices()
            If devList.Count <> 0 Then
                For Each dev As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.Device In devList
                    cmbDevice.Items.Add(dev.Name)
                Next
            End If
            If devList.Count > 0 Then
                cmbServices.Enabled = True
            End If
            btnOperation.Enabled = False
            Me.Cursor = Cursors.Default
        End Sub

        Private Sub btnOperation_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnOperation.Click
            Me.Cursor = Cursors.WaitCursor

            Select Case cmbOperation.Text
                Case "Push File"
                    openFileDialog1.Filter = "All files (*.*)|*.*"
                    If openFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                        If Not String.IsNullOrEmpty(openFileDialog1.FileName) Then
                            Try
                                If rbSync.Checked Then
                                    isAsync = False
                                    oppManager1.PushObject(openFileDialog1.FileName)
                                    Microsoft.VisualBasic.MsgBox("Object push completed. " & Environment.NewLine & "File Sent: " & _
                                                                 openFileDialog1.FileName.Substring(openFileDialog1.FileName.LastIndexOf("\") + 1), _
                                                                 Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                                                 Microsoft.VisualBasic.MsgBoxStyle.Information, "Object Push Profile")
                                Else
                                    oppManager1.PushObjectAsync(openFileDialog1.FileName, Nothing)
                                End If
                            Catch ex As Exception
                                Dim errorMsg As String = ex.Message
                                If ex.InnerException IsNot Nothing Then
                                    errorMsg = errorMsg & Environment.NewLine & "Error Details: " & ex.InnerException.Message
                                End If
                                errorMsg = errorMsg & Environment.NewLine & "Input File: " & _
                                                openFileDialog1.FileName.Substring(openFileDialog1.FileName.LastIndexOf("\") + 1)
                                Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                                             Microsoft.VisualBasic.MsgBoxStyle.Critical, "Object Push Profile")
                            End Try
                        End If
                    End If
                    Exit Select

                Case "Pull Business Card"

                    Try
                        If rbSync.Checked Then
                            isAsync = False
                            Dim cardName As String = String.Empty
                            Dim card() As Byte = Nothing
                            oppManager1.PullBusinessCard(cardName, card)
                            cardName = txtOutputFolder.Text & "\" & cardName
                            Dim i As Integer = 1
                            If IO.File.Exists(cardName) Then
                                Dim extension As String = cardName.Substring(cardName.LastIndexOf(".") + 1)
                                cardName = cardName.Remove(cardName.LastIndexOf("."))
                                While IO.File.Exists(cardName & "(" & i & ")" & "." & extension)
                                    i += 1
                                End While
                                cardName = cardName & "(" & i & ")" & "." & extension
                            End If
                            IO.File.WriteAllBytes(cardName, card)
                            Microsoft.VisualBasic.MsgBox("Business Card Pull Complete. " & Environment.NewLine & _
                                                         "Received File: " & cardName, Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                                         Microsoft.VisualBasic.MsgBoxStyle.Information, "Object Push Profile")

                        Else
                            oppManager1.PullBusinessCardAsync(Nothing)
                        End If

                    Catch ex As Exception

                        Dim errorMsg As String = ex.Message
                        If ex.InnerException IsNot Nothing Then
                            errorMsg = errorMsg & Environment.NewLine & "Error Details: " & ex.InnerException.Message
                        End If
                        Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                                     Microsoft.VisualBasic.MsgBoxStyle.Critical, "Object Push Profile")
                    End Try
                    Exit Select

                Case "Exchange Business Card"

                    openFileDialog1.Filter = "vcf files (*.vcf)|*.vcf"
                    If openFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                        If Not String.IsNullOrEmpty(openFileDialog1.FileName) Then
                            Try
                                If rbSync.Checked Then
                                    isAsync = False
                                    Dim cardName As String = String.Empty
                                    Dim card() As Byte = Nothing
                                    oppManager1.ExchangeBusinessCards(openFileDialog1.FileName, cardName, card)

                                    cardName = txtOutputFolder.Text & "\" & cardName
                                    Dim i As Integer = 1
                                    If IO.File.Exists(cardName) Then
                                        Dim extension As String = cardName.Substring(cardName.LastIndexOf(".") + 1)
                                        cardName = cardName.Remove(cardName.LastIndexOf("."))
                                        While IO.File.Exists(cardName & "(" & i & ")" & "." & extension)
                                            i += 1
                                        End While
                                        cardName = cardName & "(" & i & ")" & "." & extension
                                    End If
                                    IO.File.WriteAllBytes(cardName, card)

                                    Microsoft.VisualBasic.MsgBox("Business Card Exchange Complete. " & Environment.NewLine & "File Sent: " & _
                                                                 openFileDialog1.FileName.Substring(openFileDialog1.FileName.LastIndexOf("\")) _
                                                                 & Environment.NewLine & "Received File: " & cardName, _
                                                                 Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                                                 Microsoft.VisualBasic.MsgBoxStyle.Information, "Object Push Profile")
                                Else
                                    oppManager1.ExchangeBusinessCardsAsync(openFileDialog1.FileName, Nothing)
                                End If
                            Catch ex As Exception
                                Dim errorMsg As String = ex.Message
                                If ex.InnerException IsNot Nothing Then
                                    errorMsg = errorMsg & Environment.NewLine & "Error Details: " & ex.InnerException.Message
                                End If
                                errorMsg = errorMsg & Environment.NewLine & "Input File: " & _
                                                openFileDialog1.FileName.Substring(openFileDialog1.FileName.LastIndexOf("\") + 1)
                                Microsoft.VisualBasic.MsgBox(errorMsg, Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                                             Microsoft.VisualBasic.MsgBoxStyle.Critical, "Object Push Profile")
                            End Try
                        End If
                    End If
                    Exit Select
            End Select
            Me.Cursor = Cursors.Default
        End Sub

        Private Sub btnChangeOutputFolder_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnChangeOutputFolder.Click
            If folderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                If Not String.IsNullOrEmpty(folderBrowserDialog1.SelectedPath) Then
                    txtOutputFolder.Text = folderBrowserDialog1.SelectedPath
                Else
                    txtOutputFolder.Text = Environment.CurrentDirectory
                End If
            End If
        End Sub

        Private Sub btnExit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnExit.Click
            Disconnect()
            Me.Close()
        End Sub

		Private Sub Disconnect()
			Try
				If oppManager1.NetworkStream IsNot Nothing Then
					oppManager1.Disconnect()
                End If

			Catch ex As Exception
				btnConnect.Enabled = True
				cmbServices.Enabled = True
                Microsoft.VisualBasic.MsgBox(ex.Message, Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                             Microsoft.VisualBasic.MsgBoxStyle.Critical, "Object Push Profile")

            End Try

			Try
				If OPPService IsNot Nothing Then
					OPPService.Disconnect()
                End If

			Catch ex As Exception
				btnConnect.Enabled = True
				cmbServices.Enabled = True
                Microsoft.VisualBasic.MsgBox(ex.Message, Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                             Microsoft.VisualBasic.MsgBoxStyle.Critical, "Object Push Profile")
			End Try
		End Sub

        Private Sub cmbDevice_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles cmbDevice.SelectedIndexChanged
            Me.Cursor = Cursors.WaitCursor
            Disconnect()
            With cmbServices
                .Items.Clear()
                .Text = ""
                .Enabled = True
            End With

            btnConnect.Enabled = False
            btnOperation.Enabled = False
            Me.Cursor = Cursors.Default
        End Sub
    End Class
End Namespace
